/* eslint-disable react-hooks/exhaustive-deps */
import { Card, Button, Image, Modal, Form, Input, Upload, message, Spin } from "antd";
import { LoadingOutlined, PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';
import { GetTrademarkList, SaveOrUpdateTrademark, DeleteTrademark, TrademarkData } from '@/api/trademark/index'
// import { RcFile, UploadChangeParam, UploadFile, UploadProps } from "antd/lib/upload/interface";
import { RcFile } from "antd/lib/upload";
import { useForm } from "antd/lib/form/Form";

export default function TrademarkList() {

    // trademark列表
    const [trademarkList, setTrademarkList] = useState<TrademarkData[]>([]);
    // 当前页
    const [page, setPage] = useState(1);
    // 每页数据条数
    const [limit, setLimit] = useState(3);
    // 总条数
    const [total, setTotal] = useState(0);
    // Form加载标识
    const [spinLoading, setSpinLoading] = useState(false);
    // 添加或修改的表单数据
    const [tmInfo, setTmInfo] = useState<TrademarkData>({
        tmName: '',
        logoUrl: '',
    })
    // 判断触发pagination的onChange是否是因为改变了pagesize
    let clickIsPageSize = false

    // 获取trademark列表(可传入当前页)
    const getTrademarkList = async (page: number = 1) => {
        setPage(page);
        setSpinLoading(true);
        try {
            const result = await GetTrademarkList(page, limit);
            // 解决 Each child in a list should have a unique "key" prop 
            result.records.forEach(item => item.key = item.id);
            setTrademarkList(result.records);
            setTotal(result.total);
            setLimit(result.size);
            setSpinLoading(false);
        } catch (error) {
            message.error('获取trademark列表失败!');
            setSpinLoading(false);
        }
    }

    // 添加或修改trademark
    const addTrademark = async (trademarkInfo: TrademarkData) => {
        try {
            await SaveOrUpdateTrademark(trademarkInfo);
            if (tmInfo.id) {
                message.success('修改trademark成功!');
                getTrademarkList(page);
            } else {
                message.success('添加trademark成功!');
                getTrademarkList();
            }
        } catch (error) {
            if (tmInfo.id) {
                message.error('修改trademark失败!');
            } else {
                message.error('添加trademark失败!');
            }
            getTrademarkList();
        }
    }

    // 删除trademark
    const deleteTrademark = async (trademarkInfo: TrademarkData) => {
        try {
            await DeleteTrademark(trademarkInfo.id as number);
            message.success('删除trademark成功!');
            getTrademarkList();
        } catch (error) {
            message.error('删除trademark失败!');
            getTrademarkList();
        }
    }

    useEffect(() => {
        getTrademarkList(page);
    }, [page, limit])

    // table列配置
    const columns: ColumnsType<TrademarkData> = [
        {
            title: '序号',
            dataIndex: 'order',
            key: 'order',
            align: 'center',
            render: (text, record, index) => <span>{index + 1}</span>,
        },
        {
            title: '品牌名称',
            dataIndex: 'tmName',
            key: 'tmName',
        },
        {
            title: '品牌LOGO',
            dataIndex: 'logoUrl',
            key: 'logoUrl',
            render: (text, record, index) => {
                return (
                    <>
                        <Image width={100} src={text}></Image>
                    </>
                )
            }
        },
        {
            title: '操作',
            key: 'options',
            dataIndex: 'options',
            render: (text, record, index) => (
                <>
                    <Button onClick={() => { showModal(record) }} type="default" shape="default" size="small" style={{ borderRadius: '.25rem', backgroundColor: '#e6a23c', color: '#fff', fontSize: '.75rem', marginRight: '.625rem' }} icon={<EditOutlined />}>修改</Button>
                    <Button onClick={() => { deleteTrademark(record) }} type="default" shape="default" size="small" style={{ borderRadius: '.25rem', backgroundColor: '#f56c6c', color: '#fff', fontSize: '.75rem' }} icon={<DeleteOutlined />}>删除</Button>
                </>
            ),
        },
    ];

    // 对话框是否显示
    const [isModalOpen, setIsModalOpen] = useState(false);

    // 显示对话框的回调
    const showModal = (record: TrademarkData) => {
        form.resetFields();
        setTmInfo(record);
        // form.setFields([{ name: "tmName", value: record.tmName }, {name: "logoUrl", value: record.logoUrl}]);
        form.setFieldsValue(record);
        setIsModalOpen(true);
    };

    // 点击Modal的确定按钮的回调
    const handleOk = () => {
        form.validateFields(['tmName', 'logoUrl']);
        if (tmInfo.tmName.trim().length > 1 && tmInfo.tmName.trim().length < 9 && tmInfo.logoUrl) {
            addTrademark({ ...tmInfo, tmName: tmInfo.tmName.trim() });
            setIsModalOpen(false);
        } else {
            message.error('请正确填写数据!');
        }
    };

    // 点击Medal的取消按钮的回调
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // upload相关
    // 上传之前的校验
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('文件格式必须是JPG或PNG!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('文件不能大于2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    // 加载动画的显示状态
    const [loading, setLoading] = useState(false);

    // 使用upload组件的onChange处理上传状态
    // const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    //     if (info.file.status === 'uploading') {
    //         setLoading(true);
    //         return;
    //     }
    //     if (info.file.status === 'done') {
    //         // Get this url from response in real world.
    //         setLoading(false);
    //         setTmInfo({ ...tmInfo, logoUrl: info.file.response.data });
    //     }
    // };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    // 收集tmName
    const inputTmName = (e: any) => {
        setTmInfo({ ...tmInfo, tmName: e.target.value });
    }

    // 定义form表单实例
    const [form] = useForm();

    // 解决Upload在Form.Item中,给Form.Item设置了name之后报错 Uncaught TypeError: (fileList || []).forEach is not a function 
    // 使用Form.Item组件的getValueFromEvent处理上传状态
    const normFile = (e: any) => {
        // console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        if (e.file.status === "uploading"){
            setLoading(true);
            return;
        }
        if (e.file.status === "done"){
            setLoading(false);
            setTmInfo({ ...tmInfo, logoUrl: e.file.response.data });
        }
        return e && e.fileList;
    };

    return (
        <>
            <Card>
                <Modal width={756} title={tmInfo.id ? '修改品牌' : '添加品牌'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                    <Form form={form}>
                        <Form.Item label="品牌名称" name="tmName" rules={[{ required: true, message: '品牌名称必须填写!' }, { type: 'string', min: 2, max: 8, message: '名称长度为2~8字符' }, { type: 'string', whitespace: true, message: '不允许只输入空格' }]}>
                            <Input
                                value={tmInfo.tmName} onChange={inputTmName}
                            />
                        </Form.Item>
                        <Form.Item label="品牌LOGO"
                            getValueFromEvent={normFile}
                            name="logoUrl"
                            valuePropName="logoUrl"
                            rules={[{ required: true, message: '品牌LOGO必须上传!' }]}>
                            <Upload
                                listType="picture-card"
                                className="avatar-uploader"
                                showUploadList={false}
                                action="/app-api/admin/product/upload"
                                beforeUpload={beforeUpload}
                                // onChange={handleChange}
                            >
                                {tmInfo.logoUrl ? <img src={tmInfo.logoUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                            </Upload>
                        </Form.Item>
                        <span style={{ fontSize: '.75rem' }}>上传的图片必须是jpg且不能大于2M</span>
                    </Form>
                </Modal>
                <Button type="default" shape="default" size="middle" style={{ borderRadius: '.25rem', backgroundColor: '#3f9eff', color: '#fff', fontSize: '.875rem' }} icon={<PlusOutlined />} onClick={() => { showModal({ tmName: '', logoUrl: '' }) }}>添加</Button>
            </Card>
            <Spin spinning={spinLoading}>
                <Card>
                    <Table columns={columns} dataSource={trademarkList} bordered pagination={{
                        total: total,
                        current: page,
                        onChange(page: number, pageSize: number) {
                            if (clickIsPageSize) {
                                setPage(1);
                                setLimit(pageSize);
                                clickIsPageSize = false
                            } else {
                                setPage(page);
                                clickIsPageSize = false
                            }

                        },
                        onShowSizeChange() {
                            clickIsPageSize = true
                        },
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: ['3', '5', '7', '10'],
                        pageSize: limit,
                        showTotal: total => `共 ${total} 条`
                    }} />
                </Card>
            </Spin>
        </>
    )
}